const express = require('express');
const router = express.Router();
const { Dict, DictItem } = require('../models/dict');

// 生成自定义ID
function generateCustomId() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `${timestamp}${random}`;
}

// 获取字典列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, code, status } = req.query;

    // 构建查询条件
    const query = {};
    if (name) {
      query.name = new RegExp(name, 'i');
    }
    if (code) {
      query.code = new RegExp(code, 'i');
    }
    if (status !== undefined) {
      query.status = status === 'true';
    }

    const total = await Dict.countDocuments(query);
    const list = await Dict.find(query)
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: -1 });

    res.json({
      success: true,
      data: {
        list,
        total,
      },
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      message: '获取列表失败',
    });
  }
});

// 创建字典
router.post('/create', async (req, res) => {
  try {
    const { name, code, sort = 0, status = true, remark } = req.body;

    // 检查是否已存在相同的编码
    const existing = await Dict.findOne({ code });
    if (existing) {
      return res.status(400).json({
        code:500,
        message: '字典编码已存在',
      });
    }

    const dict = new Dict({
      id: generateCustomId(), // 使用自定义ID
      name,
      code,
      sort,
      status,
      remark,
    });

    await dict.save();

    res.json({
      success: true,
      data: dict,
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      message: '创建失败',
    });
  }
});

// 更新字典
router.post('/update', async (req, res) => {
  try {
    const { id, name, code, sort, status, remark } = req.body;

    // 检查是否存在相同的编码（排除自身）
    const existing = await Dict.findOne({ code, id: { $ne: id } });
    if (existing) {
      return res.status(400).json({
        code:500,
        message: '字典编码已存在',
      });
    }

    const dict = await Dict.findOneAndUpdate(
      { id }, // 使用自定义ID查询
      { name, code, sort, status, remark },
      { new: true }
    );

    if (!dict) {
      return res.status(404).json({
        code:500,
        message: '字典不存在',
      });
    }

    res.json({
      success: true,
      data: dict,
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      message: '更新失败',
    });
  }
});

// 删除字典
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;

    // 检查是否有关联的字典项
    const itemCount = await DictItem.countDocuments({ dictId: id });
    if (itemCount > 0) {
      return res.status(400).json({
        code:500,
        message: '该字典下存在字典项，无法删除',
      });
    }

    const dict = await Dict.findOneAndDelete({ id }); // 使用自定义ID删除
    if (!dict) {
      return res.status(404).json({
        code:500,
        message: '字典不存在',
      });
    }

    res.json({
      success: true,
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      message: '删除失败',
    });
  }
});

// 获取字典项列表
router.get('/items', async (req, res) => {
  try {
    const { dictId, page = 1, pageSize = 10 } = req.query;
    
    if (!dictId) {
      return res.status(400).json({
        code:500,
        message: '字典ID不能为空'
      });
    }

    const query = { dictId };
    const total = await DictItem.countDocuments(query);
    const list = await DictItem.find(query)
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: 1, createdAt: -1 });

    res.json({
      success: true,
      data: {
        list,
        total,
        page: Number(page),
        pageSize: Number(pageSize)
      }
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 字典子项列表
router.get('/item/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, dictId, dictCode, label, value, status } = req.query;

    if (!dictId && !dictCode) {
      return res.status(400).json({
        code:500,
        message: '字典ID或字典编码不能为空',
      });
    }

    // 构建查询条件
    let query = {};

    // 如果提供了dictId，直接使用
    if (dictId) {
      query.dictId = dictId;
    }
    // 如果提供了dictCode，先查询字典获取id
    else if (dictCode) {
      const dict = await Dict.findOne({ code: dictCode });
      if (!dict) {
        return res.status(404).json({
          code:500,
          message: '字典不存在',
        });
      }
      query.dictId = dict.id;
    }

    if (label) {
      query.label = new RegExp(label, 'i');
    }
    if (value) {
      query.value = new RegExp(value, 'i');
    }
    if (status !== undefined) {
      query.status = status === 'true';
    }

    const total = await DictItem.countDocuments(query);
    const list = await DictItem.find(query)
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: -1 });

    res.json({
      success: true,
      code: 200,
      message: '操作成功',
      data: {
        list,
        total,
        page: Number(page),
        pageSize: Number(pageSize),
      },
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      code: 500,
      message: '获取列表失败',
    });
  }
});

// 创建字典项
router.post('/item/create', async (req, res) => {
  try {
    const { dictId, label, value, sort = 0, status = true, remark } = req.body;

    // 检查字典是否存在
    const dict = await Dict.findOne({ id: dictId });
    if (!dict) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '字典不存在',
      });
    }

    // 检查同一字典下是否存在相同的标签或值
    const existing = await DictItem.findOne({
      dictId,
      $or: [{ label }, { value }],
    });
    if (existing) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '标签或值已存在',
      });
    }

    const dictItem = new DictItem({
      id: generateCustomId(), // 使用自定义ID
      dictId,
      label,
      value,
      sort,
      status,
      remark,
    });

    await dictItem.save();

    res.json({
      success: true,
      code: 200,
      message: '创建成功',
      data: dictItem,
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      code: 500,
      message: '创建失败',
    });
  }
});

// 更新字典项
router.post('/item/update', async (req, res) => {
  try {
    const { id, dictId, label, value, sort, status, remark } = req.body;

    // 检查字典项是否存在
    const item = await DictItem.findOne({ id });
    if (!item) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '字典项不存在',
      });
    }

    // 检查dictId是否匹配
    if (item.dictId !== dictId) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '字典ID不匹配',
      });
    }

    // 检查同一字典下是否存在相同的标签或值（排除自身）
    const existing = await DictItem.findOne({
      dictId,
      $or: [{ label }, { value }],
      id: { $ne: id },
    });
    if (existing) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '标签或值已存在',
      });
    }

    const updated = await DictItem.findOneAndUpdate(
      { id },
      { label, value, sort, status, remark },
      { new: true }
    );

    res.json({
      success: true,
      code: 200,
      message: '更新成功',
      data: updated,
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      code: 500,
      message: '更新失败',
    });
  }
});

// 删除字典项
router.post('/item/delete', async (req, res) => {
  try {
    const { id } = req.body;

    // 检查字典项是否存在
    const item = await DictItem.findOne({ id });
    if (!item) {
      return res.status(400).json({
        code:500,
        code: 400,
        message: '字典项不存在',
      });
    }

    // TODO: 这里可以添加检查字典项是否被引用的逻辑

    await DictItem.findOneAndDelete({ id });

    res.json({
      success: true,
      code: 200,
      message: '删除成功',
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      code:500,
      code: 500,
      message: '删除失败',
    });
  }
});

module.exports = router; 